package com.foreverwin.mes.production.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.production.mapper.WorkDayRestTimeDetailMapper;
import com.foreverwin.mes.production.mapper.WorkDayRestTimeMapper;
import com.foreverwin.mes.production.model.WorkDayRestTime;
import com.foreverwin.mes.production.model.WorkDayRestTimeDetail;
import com.foreverwin.mes.production.model.WorkDayRestTimeDetailView;
import com.foreverwin.mes.production.service.WorkDayRestTimeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class WorkDayRestTimeServiceImpl extends ServiceImpl<WorkDayRestTimeMapper, WorkDayRestTime> implements WorkDayRestTimeService {


    @Autowired
    private WorkDayRestTimeMapper workDayRestTimeMapper;

    @Autowired
    private WorkDayRestTimeDetailMapper workDayRestTimeDetailMapper;

    @Override
    public Page<WorkDayRestTime> selectPage(FrontPage<WorkDayRestTime> frontPage) {
        EntityWrapper<WorkDayRestTime> entityWrapper = new EntityWrapper<WorkDayRestTime>();
        //getEntityWrapper(entityWrapper, workDayRestTime);
        return super.selectPage(frontPage.getPagePlus(), entityWrapper);
    }

    @Override
    public List<WorkDayRestTime> selectList() {
        EntityWrapper<WorkDayRestTime> entityWrapper = new EntityWrapper<WorkDayRestTime>();
        //getEntityWrapper(entityWrapper, workDayRestTime);
        return super.selectList(entityWrapper);
    }


    /**
     * 查询工作日休息数据
     *
     * @param site
     * @param workCenter
     * @return
     */
    @Override
    public WorkDayRestTime getWorkDayRestTimeData(String site, String workCenter) {

        String handle = "WorkCenterBO:" + site + "," + workCenter;
        WorkDayRestTime workDayRestTime = workDayRestTimeMapper.selectById(handle);
        if (workDayRestTime == null) { //说明未维护休息时间数据
            return null;
        }

        //查询明细表数据
        EntityWrapper<WorkDayRestTimeDetail> wrapper = new EntityWrapper<WorkDayRestTimeDetail>();
        wrapper.eq("WORK_DAY_REST_TIME_BO", handle);
        wrapper.orderBy("CREATED_DATE_TIME");
        List<WorkDayRestTimeDetail> workDayRestTimeDetailList = workDayRestTimeDetailMapper.selectList(wrapper);
        workDayRestTime.setWorkDayRestTimeDetailList(workDayRestTimeDetailList);

        return workDayRestTime;

    }


    /**
     * 保存工作日休息数据
     *
     * @param site
     * @param userId
     * @param workCenter
     * @param startTime
     * @param endTime
     * @param modifiedDateTime
     * @return
     */
    @Override
    public void saveWorkDayRestData(String site, String userId, String workCenter, String startTime, String endTime, String modifiedDateTime) throws BusinessException {

        String handle = "WorkCenterBO:" + site + "," + workCenter;
        WorkDayRestTime workDayRestTimeModel = workDayRestTimeMapper.selectForUpdateById(handle);
        if (workDayRestTimeModel == null) { //代表该工作中心休息数据未维护

            //组装主表数据
            Date date = new Date();
            WorkDayRestTime workDayRestTime = new WorkDayRestTime();
            workDayRestTime.setHandle(handle);
            workDayRestTime.setSite(site);
            workDayRestTime.setWorkCenter(workCenter);
            workDayRestTime.setCreator(userId);
            workDayRestTime.setCreatedDateTime(date);
            workDayRestTime.setUpdater(userId);
            workDayRestTime.setModifiedDateTime(date);

            //组装字表数据
            WorkDayRestTimeDetail workDayRestTimeDetail = new WorkDayRestTimeDetail();
            workDayRestTimeDetail.setHandle(handle + "," + startTime + "," + endTime);
            workDayRestTimeDetail.setSite(site);
            workDayRestTimeDetail.setWorkDayRestTimeBo(handle);
            workDayRestTimeDetail.setRestStartTime(startTime);
            workDayRestTimeDetail.setRestEndTime(endTime);
            workDayRestTimeDetail.setStatus("");
            workDayRestTimeDetail.setCreatedDateTime(date);
            workDayRestTimeDetail.setModifiedDateTime(date);

            //保存数据
            workDayRestTimeMapper.insert(workDayRestTime);
            workDayRestTimeDetailMapper.insert(workDayRestTimeDetail);

        } else { //代表该工作中心休息数据已维护

            Date modifyTime = workDayRestTimeModel.getModifiedDateTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            String formatStr = format.format(modifyTime);
            if (!formatStr.equals(modifiedDateTime)) {

                throw BusinessException.build("数据已被修改，请重新检索");
            }
            validateCrossSetting(workDayRestTimeModel.getHandle(), handle + "," + startTime + "," + endTime, startTime, endTime);
            Date date = new Date();
            workDayRestTimeModel.setModifiedDateTime(date);
            workDayRestTimeModel.setUpdater(userId);
            EntityWrapper<WorkDayRestTime> wrapper = new EntityWrapper<WorkDayRestTime>();
            wrapper.eq("HANDLE", workDayRestTimeModel.getHandle());

            //组装字表数据
            WorkDayRestTimeDetail workDayRestTimeDetail = new WorkDayRestTimeDetail();
            workDayRestTimeDetail.setHandle(handle + "," + startTime + "," + endTime);
            workDayRestTimeDetail.setSite(site);
            workDayRestTimeDetail.setWorkDayRestTimeBo(handle);
            workDayRestTimeDetail.setRestStartTime(startTime);
            workDayRestTimeDetail.setRestEndTime(endTime);
            workDayRestTimeDetail.setStatus("");
            workDayRestTimeDetail.setCreatedDateTime(date);
            workDayRestTimeDetail.setModifiedDateTime(date);

            workDayRestTimeMapper.update(workDayRestTimeModel, wrapper);
            workDayRestTimeDetailMapper.insert(workDayRestTimeDetail);
        }

    }


    /**
     * 更新工作日休息数据
     *
     * @param site
     * @param userId
     * @param workCenter
     * @param detailHandle
     * @param startTime
     * @param endTime
     * @param modifiedDateTime
     * @throws BusinessException
     */
    @Override
    public void updateWorkDayRestData(String site, String userId, String workCenter, String detailHandle, String startTime, String endTime, String modifiedDateTime) throws BusinessException {

        String handle = "WorkCenterBO:" + site + "," + workCenter;
        WorkDayRestTime workDayRestTimeModel = workDayRestTimeMapper.selectForUpdateById(handle);
        if (workDayRestTimeModel == null) { //代表该工作中心休息数据未维护

            throw BusinessException.build("数据未维护请重新检索");

        } else { //代表该工作中心休息数据已维护

            Date modifyTime = workDayRestTimeModel.getModifiedDateTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            String formatStr = format.format(modifyTime);
            if (!formatStr.equals(modifiedDateTime)) {

                throw BusinessException.build("数据已被修改，请重新检索");
            }
            validateCrossSetting(workDayRestTimeModel.getHandle(), detailHandle, startTime, endTime);
            Date date = new Date();
            workDayRestTimeModel.setModifiedDateTime(date);
            workDayRestTimeModel.setUpdater(userId);
            EntityWrapper<WorkDayRestTime> wrapper = new EntityWrapper<WorkDayRestTime>();
            wrapper.eq("HANDLE", workDayRestTimeModel.getHandle());

            workDayRestTimeMapper.update(workDayRestTimeModel, wrapper);
            workDayRestTimeDetailMapper.updateRestTimeDetail(detailHandle, (handle + "," + startTime + "," + endTime), startTime, endTime, date);

        }

    }

    public void validateCrossSetting(String workDayRestTimeHandle, String detailHandle, String startTime, String endTime) throws BusinessException {
        List<WorkDayRestTimeDetail> workDayRestTimeDetailList = workDayRestTimeDetailMapper.selectList(new EntityWrapper<WorkDayRestTimeDetail>().eq("WORK_DAY_REST_TIME_BO", workDayRestTimeHandle));
        Integer currentStartMinutes = Integer.parseInt(startTime.split(":")[0].trim()) * 60 + Integer.parseInt(startTime.split(":")[1].trim());
        Integer currentEndMinutes = Integer.parseInt(endTime.split(":")[0].trim()) * 60 + Integer.parseInt(endTime.split(":")[1].trim());
        Integer nextStartMinutes = null;
        Integer nextEndMinutes = null;
        if (currentStartMinutes > currentEndMinutes) {
            //currentEndMinutes = currentEndMinutes + 24 * 60;
            nextStartMinutes = 0;
            nextEndMinutes = currentEndMinutes;

            currentEndMinutes = 24 * 60;
        }
        List<WorkDayRestTimeDetailView> newList = new ArrayList<>();
        if (workDayRestTimeDetailList != null && workDayRestTimeDetailList.size() > 0) {
            for (WorkDayRestTimeDetail workDayRestTimeDetail : workDayRestTimeDetailList) {
                if (workDayRestTimeDetail.getHandle().equals(detailHandle)) {
                    continue;
                }
                String[] restStartTimeArray = workDayRestTimeDetail.getRestStartTime().split(":");
                String[] restEndTimeArray = workDayRestTimeDetail.getRestEndTime().split(":");
                int startMinutes = Integer.parseInt(restStartTimeArray[0].trim()) * 60 + Integer.parseInt(restStartTimeArray[1].trim());
                int endMinutes = Integer.parseInt(restEndTimeArray[0].trim()) * 60 + Integer.parseInt(restEndTimeArray[1].trim());
                if (startMinutes > endMinutes) {
                    //endMinutes = endMinutes + 24 * 60;
                    WorkDayRestTimeDetailView newWorkDayRestTimeDetail = new WorkDayRestTimeDetailView();
                    BeanUtils.copyProperties(workDayRestTimeDetail, newWorkDayRestTimeDetail);
                    newWorkDayRestTimeDetail.setStartMinute(0);
                    newWorkDayRestTimeDetail.setEndMinute(endMinutes);
                    newList.add(newWorkDayRestTimeDetail);
                    endMinutes = 24 * 60;
                }
                WorkDayRestTimeDetailView newWorkDayRestTimeDetail = new WorkDayRestTimeDetailView();
                BeanUtils.copyProperties(workDayRestTimeDetail, newWorkDayRestTimeDetail);
                newWorkDayRestTimeDetail.setStartMinute(startMinutes);
                newWorkDayRestTimeDetail.setEndMinute(endMinutes);
                newList.add(newWorkDayRestTimeDetail);
            }

            for (WorkDayRestTimeDetailView workDayRestTimeDetail : newList) {
                if (workDayRestTimeDetail.getHandle().equals(detailHandle)) {
                    continue;
                }
                int startMinutes = workDayRestTimeDetail.getStartMinute();
                int endMinutes = workDayRestTimeDetail.getEndMinute();

                if ((startMinutes > currentStartMinutes && startMinutes < currentEndMinutes) ||
                        (endMinutes > currentStartMinutes && endMinutes < currentEndMinutes) ||
                        (startMinutes < currentStartMinutes && endMinutes >= currentEndMinutes) ||
                        (startMinutes <= currentStartMinutes && endMinutes > currentEndMinutes)) {
                    throw BusinessException.build("存在与当前时间交叉的休息时间设定：[" + workDayRestTimeDetail.getRestStartTime() + ">>>" + workDayRestTimeDetail.getRestEndTime() + "]");
                }
                if (nextStartMinutes != null && nextEndMinutes != null) {
                    if ((startMinutes > nextStartMinutes && startMinutes < nextEndMinutes) ||
                            (endMinutes > nextStartMinutes && endMinutes < nextEndMinutes) ||
                            (startMinutes < nextStartMinutes && endMinutes >= nextEndMinutes) ||
                            (startMinutes <= nextStartMinutes && endMinutes > nextEndMinutes)) {
                        throw BusinessException.build("存在与当前时间交叉的休息时间设定：[" + workDayRestTimeDetail.getRestStartTime() + ">>>" + workDayRestTimeDetail.getRestEndTime() + "]");
                    }
                }
            }
        }
    }

    /**
     * 删除工作日休息数据
     *
     * @param site
     * @param user
     * @param workCenter
     * @param modifiedDateTime
     * @param detailHandleList
     * @throws BusinessException
     */
    @Override
    public void deleteWorkDayRestData(String site, String user, String workCenter, String modifiedDateTime,
                                      List<String> detailHandleList) throws BusinessException {

        String handle = "WorkCenterBO:" + site + "," + workCenter;

        WorkDayRestTime workDayRestTime = workDayRestTimeMapper.selectForUpdateById(handle);
        Date modifyTime = workDayRestTime.getModifiedDateTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String formatStr = format.format(modifyTime);
        if (!formatStr.equals(modifiedDateTime)) {

            throw BusinessException.build("数据已被修改，请重新检索");
        }

        //删除明细表数据
        workDayRestTimeDetailMapper.deleteBatchIds(detailHandleList);

        //查询明细表数据
        EntityWrapper<WorkDayRestTimeDetail> wrapper = new EntityWrapper<WorkDayRestTimeDetail>();
        wrapper.eq("WORK_DAY_REST_TIME_BO", handle);
        wrapper.orderBy("CREATED_DATE_TIME");
        List<WorkDayRestTimeDetail> workDayRestTimeDetailList = workDayRestTimeDetailMapper.selectList(wrapper);
        if (workDayRestTimeDetailList.size() == 0) { //删除主表数据

            workDayRestTimeMapper.deleteById(handle);

        } else { //跟新主表数据

            workDayRestTimeMapper.updateWorkDayRestTime(handle, new Date(), user);

        }


    }

}